
package com.platform.modules.mall.service.impl;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.common.validator.AbstractAssert;
import com.platform.modules.mall.dao.MallUserDao;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.MallUserService;
import com.platform.modules.oss.cloud.UploadFactory;
import com.platform.modules.oss.entity.SysOssEntity;
import com.platform.modules.oss.service.SysOssService;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Service("userService")
public class MallUserServiceImpl extends ServiceImpl<MallUserDao, MallUserEntity> implements MallUserService {
    @Autowired
    JedisUtil jedisUtil;

    @Autowired
    private SysOssService sysOssService;

    @Override
    public List<MallUserEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public boolean setUserInfo(Map<String, Object> params) {
        String userId = params.get("id").toString();
        ValidUtils.allNotNull(userId);

        LambdaUpdateWrapper<MallUserEntity> updateWrapper = new LambdaUpdateWrapper<>();
        boolean exec = false;
        MultipartFile file = (MultipartFile) params.get("file");
        if (file != null && !file.isEmpty()) {
            String url;
            if (file.getSize() > 5242880) {
                throw new BusinessException("头像不能大于 5M");
            }
            String suffix = FileUtil.extName(file.getOriginalFilename());
            if (!StrUtil.equalsAnyIgnoreCase(suffix, Constant.IMAGE_EXTNAME)) {
                throw new BusinessException("仅支持jpg或png格式");
            }
            byte[] fileByte = null;
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                // 图片压缩
                Img.from(file.getInputStream())
                        .setQuality(0.5)//压缩比率
                        .write(outputStream);
                fileByte = outputStream.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    fileByte = file.getBytes();
                } catch (Exception e1) {
                    e1.printStackTrace();
                    throw new BusinessException(e.getMessage());
                }
            }
            try {
                //上传文件
                url = UploadFactory.build().uploadSuffix(fileByte, "."+suffix);
                //保存文件信息
                SysOssEntity ossEntity = new SysOssEntity();
                ossEntity.setUrl(url);
                ossEntity.setCreateDate(new Date());
                sysOssService.save(ossEntity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("头像上传失败！");
            }
            updateWrapper.set(MallUserEntity::getHeadImgUrl, url);
            exec = true;
        }
        String name = (String) params.get("name");
        if (StringUtils.isNotBlank(name)) {
            updateWrapper.set(MallUserEntity::getNickname, name);
            exec = true;
        }
        if (exec) {
            updateWrapper.eq(MallUserEntity::getId, userId);
        } else {
            throw new BusinessException("参数错误！");
        }
        return this.update(updateWrapper);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.REGISTER_TIME");
        params.put("asc", false);
        Page<MallUserEntity> page = new Query<MallUserEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallUserPage(page, params));
    }

    @Override
    public boolean add(MallUserEntity mallUser) {
        return this.save(mallUser);
    }

    @Override
    public boolean update(MallUserEntity mallUser) {
        return this.updateById(mallUser);
    }

    @Override
    public boolean delete(Integer id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public MallUserEntity queryByMobile(String mobile) {
        return this.getOne(new QueryWrapper<MallUserEntity>().eq("MOBILE", mobile), false);
    }

    @Override
    public MallUserEntity loginByMobile(String mobile, String password) {
        MallUserEntity user = queryByMobile(mobile);
        AbstractAssert.isNull(user, "该手机暂未绑定用户");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new BusinessException("手机号或密码错误");
        }

        return user;
    }

    @Override
    public MallUserEntity selectByOpenId(String openId) {
        MallUserEntity userEntity = new MallUserEntity();
        userEntity.setOpenId(openId);
        return baseMapper.selectOne(new QueryWrapper<MallUserEntity>().eq("OPEN_ID", openId));
    }

    @Override
    public MallUserEntity saveOrUpdateByOpenId(WxOAuth2UserInfo userWxInfo) {
        MallUserEntity entity = this.getOne(new QueryWrapper<MallUserEntity>().eq("OPEN_ID", userWxInfo.getOpenid()));
        if (entity == null) {
            entity = new MallUserEntity();
            entity.setRegisterTime(new Date());
        }
        entity.setNickname(userWxInfo.getNickname());
        entity.setHeadImgUrl(userWxInfo.getHeadImgUrl());
        entity.setOpenId(userWxInfo.getOpenid());
        entity.setGender(userWxInfo.getSex());
        this.saveOrUpdate(entity);
        return entity;
    }
}
